<template>
  <view class="definite">
    <u-navbar :is-back="true" :custom-back="BackM" title="确认订单" back-text="">
    </u-navbar>
    <view class="top" style="display: flex;align-items: center;" @click="addressM">
      <u-icon name="map" color="#02CB86" class="map" size="50"></u-icon>

      <view v-if="!addressFlag" >添加新地址</view>
	  
      <view v-if="addressFlag">
        <view class="item">
          <span>收货人：</span>
          <span class="name">{{addressDic.name}}</span>
          <span class="tele">{{addressDic.phone}}</span>
        </view>
        <view class="address">
          <span>收货地址：</span>
          <span>{{addressDic.address}}</span>
        </view>
      </view>
	  
	  
      <image class="top-image" src="../../style/image/my/A15.png" alt="" />
	  
    </view>
	
	
	
    <view class="item-content" v-for="(item,index) in carGoods " :key='index' >
      <view class="image">
        <image :src="item.posType.image" alt="" />
      </view>
      <view class="description">{{item.posType.modelsName}}</view>
      <!-- <view class="type">无</view> -->
      <view>
        <span class="money">¥ {{item.price}}</span>
        <span class="num">×{{item.num}}</span>
      </view>
    </view>
	
	
    <!-- <view class="item-one">
      <span>优惠券</span>
      <span class="null">暂无可用优惠券</span>
      <image class="image-one" src="../../style/image/my/A15.png" alt="" />
    </view> -->
	
    <view @click="distrM" class="item-one">
      <span>配送方式</span>
      <span class="have">{{fastMailName}}</span>
      <image class="image-one" src="../../style/image/my/A15.png" alt="" />
    </view>
    <view v-if="fastMailName != '自提'" class="item-one">
      <span>运费</span>
      <span style="float: right">￥{{postMoney}}</span>
    </view>
    <view class="item-two">
      <view class="total">
        <span style="padding-right: 0.7rem">共{{carGoods.length}}件商品</span>
        <span>小计：</span>
        <span style="color: #ff0000; font-size: 0.8rem">￥{{tipMoney}}</span>
      </view>
    </view>

    <view class="item-one">选择支付方式</view>

    <view class="item-one" @click="payTypeClick('ye')">
      <image class="one-image" src="../../style/image/order/yue.png" alt="" />
      <span style="padding-left: 1.8rem">余额支付¥({{allYuMoney}})</span>
      <image v-if="payType != 'ye'" class="two-image" src="../../style/image/cargo/round.png" alt="" />
	     <image v-if="payType == 'ye'" class="two-image" src="../../style/image/cargo/selectRound.png" alt="" />
    </view>
    <!-- <view class="item-one" @click="payTypeClick('wx')">
      <image class="three-image" src="../../style/image/order/C2.png" alt="" />
      <span style="padding-left: 1.8rem">微信支付</span>
      <image v-if="payType != 'wx'" class="two-image" src="../../style/image/my/A37.jpg" alt="" />
	  <image v-if="payType == 'wx'" class="two-image" src="../../style/image/my/A38.jpg" alt="" />
    </view> -->
    <view class="item-one" @click="payTypeClick('zfb')" style="margin-bottom: 3rem;">
      <image class="three-image" src="../../style/image/order/apily.png" alt="" />
      <span style="padding-left: 1.8rem">支付宝支付</span>
      <image v-if="payType != 'zfb'" class="two-image" src="../../style/image/cargo/round.png" alt="" />
	     <image v-if="payType == 'zfb'" class="two-image" src="../../style/image/cargo/selectRound.png" alt="" />
    </view>

    <!-- <view class="btn">
      <span>合计: </span>
      <span style="color: #fe4646">￥0 </span>
      <button class="button">提醒发货</button>
    </view> -->
    <view class="footP">
		<view @click="addPay" style=" height: 3rem; line-height: 3rem; display: flex; align-items: center;
									justify-content: space-between; width: 100%; ">
			<!-- <image style="width: 1rem;" src="../../style/image/cargo/add.jpg" alt=""> -->
			<view style="margin-left: 0.2rem; display: flex; align-items: center">
			  <!-- <image style="width: 1rem; height: 1rem" src="../../style/image/cargo/selectRound.png" alt="" /> -->
			  <!-- <view style=" font-size: 0.7rem; font-family: PingFang SC; font-weight: 300; color: #666666;
				  margin-left: 0.5rem; " > 全选 </view> -->
			</view>

			<view class="foot-right" style="margin-right: 0rem">
			  <view style="font-size: 0.73rem; font-family: PingFang SC; font-weight: 300;">
				合计:<span style="color: red">¥{{allMoney}}</span>
			  </view>
			  <view class="settle">确认支付</view>
			</view>
		</view>
    </view>

    <u-popup v-model="paySuccess.show" mode="center">
      <view class="imageP">
        <image style="width: 16rem" src="../../style/image/order/apilySuccess.png" alt="" />
      </view>

      <view class="threeQ" style="color: white">
        <view @click="payClick" style=" text-align: center; border: 1px solid rgb(255, 255, 255);
            border-radius: 1rem; padding: 0.5rem 2rem; margin: 1rem; " >
          <!-- <image class="threeQ-image"  src="../../style/image/share/local.jpg" alt=""> -->
          <view>{{paySuccess.label}}</view>
        </view>
      </view>
    </u-popup>

    <u-action-sheet :list="sheetList" v-model="sheetShow" @click="sheetClick"></u-action-sheet>
  </view>
</template>

<script lang='ts' >
import { Component, Prop, Vue, Watch, Emit } from "vue-property-decorator";

import { AppModule } from "../../store/modules/app";

import { findAddress } from "../../utils/uniApi";
import { freightCalculate } from "../../utils/uniApi";
import { findUserMoney } from "../../utils/uniApi";

import { saveOrder } from "../../utils/uniApi";
import { saveOrderByBalance } from "../../utils/uniApi";
import { aliPay } from "../../utils/uniApi";

@Component({
  //   @Component  是一个装修器   不可以在下面写语句
  name: "test",
})
export default class extends Vue {
  @Prop({
    type: String, // 父组件传递给子组件的数据类型
    required: false, // 是否必填
    default: " ", // 默认值， 如果传入的是 Object，则要 default: ()=>({}) 参数为函数
  })
  msg!: string;
  
  public loginData:any = {};//

  public addressFlag = false;//是否有地址
  public addressDic:any = {};//地址
  public carGoods:any=[];//购物车商品list
  public carGoodsids:any=[];//购物车商品id的集合
  public postMoney:any=0.00;//运费
  public tipMoney:any=0.00;//小计
  public allMoney:any=0;//合计总价
  public payType:any='ye';//ye:余额  wx:微信  zfb:支付宝
  public allYuMoney:any=0.00;//可用余额
  
  public orderNum:any;//可用余额

  public paySuccess = {show:false,label:'完成'};   //购买成功的弹框
  
  public fastMailName:any='普通快递';//配送方式

  public sheetList = [
    {
      text: "自提",
    },
    {
      text: "普通快递",
    },
  ];
  public sheetShow = false;//邮寄方式的地步弹窗

  created() {}
  
  onHide(){
  	  uni.hideLoading();
  }
  
  //下拉刷新
  onPullDownRefresh() {
      setTimeout(function () {
        uni.redirectTo({
          url: "../../pages/order/sureOrder",
        });
        uni.stopPullDownRefresh();
      }, 1000);
  }
  
  onLoad(value:any){
	  if(value.goods){
		  let dic:any = JSON.parse(decodeURIComponent(value.goods))
		  uni.setStorage({
		    key: "sureOrderData",
		    data: dic,
		    success: function () {
		    },
		  });
		  this.carGoods = dic.list;
		  this.tipMoney = parseFloat(dic.all);
		  this.allMoney = parseFloat(this.tipMoney);
		  this.carGoods.map((val:any, idx:any) => {
		  	this.carGoodsids.push(val.id)
		  })
	  }else{
		  var dataDic = uni.getStorageSync("sureOrderData")
		  this.carGoods = dataDic.list;
		  this.tipMoney = parseFloat(dataDic.all);
		  this.allMoney = parseFloat(this.tipMoney);
		  this.carGoods.map((val:any, idx:any) => {
		  	this.carGoodsids.push(val.id)
		  })
	  }
	  
	// let dic:any = JSON.parse(decodeURIComponent(value.goods))
	// this.carGoods = dic.list;
	// this.tipMoney = parseFloat(dic.all);
	// this.allMoney = parseFloat(this.tipMoney);
	// this.carGoods.map((val:any, idx:any) => {
	// 	this.carGoodsids.push(val.id)
	// })
  	
	this.loginData = uni.getStorageSync("otherData")
	var timestr = new Date().valueOf()//
	var phone = this.loginData.phone
	this.orderNum = 'O'+timestr+phone.substr(-4,4);
  }
  
  onShow(){
	  this.findAddress();
	  this.freightCalculate(this.carGoodsids)
	  this.findUserMoney()
  }

  mounted() {
    //  console.log('父组件传递的参数:',this.$parent)   //暂时不考虑
    //  uni.navigateTo({
    // url: './selectBusin'
    // });
  }
  
  //拉取地址的数据
  findAddress(){
	  uni.showLoading({
	  	title: '加载中'
	  });
  	  let params = {
  		userId:uni.getStorageSync("userId") == ""? "": parseInt(uni.getStorageSync("userId")),
  	  };
  	  findAddress(params).then((res: any) => {
  	    console.log('++++++++++++++++++++地址数据列表：' + JSON.stringify(res.data) )
  	      if(res.data.code==200){
			  var hasDefault = false
			  if(res.data.data.length>0){
				  this.addressFlag = true
				  res.data.data.map((val:any, idx:any) => {
				  	if(val.defaultAddress == 0){
						hasDefault = true;
				  		this.addressDic = val;
				  	}
				  })
				  if(!hasDefault){
					  this.addressDic = res.data.data[0];
				  }
			  }else{
				  this.addressFlag = false
			  }
  			  uni.hideLoading();
  	      }else{
			  uni.hideLoading();
			  uni.showToast({
			  	title: '数据加载失败',
			  	icon: 'none',
			  	duration: 2000
			  });
  	      }
  	  });
  }
  
  //计算邮费
  freightCalculate(ids:any){
  	  let params = {
		goodsCartIds:JSON.stringify(ids),
  		userId:uni.getStorageSync("userId") == ""? "": parseInt(uni.getStorageSync("userId")),
  	  };
  	  freightCalculate(params).then((res: any) => {
  	    // console.log('++++++++++++++++++++邮费数据：' + JSON.stringify(res.data) )
  	      if(res.data.code==200){
  			  this.postMoney = res.data.data;
  	      }else{
  	      
  	      }
  	  });
  }
  //计算余额
  findUserMoney(){

	  var type = this.loginData.loginStatus=='porxy'?0:1;
    
  	  let params = {
		type:type,//登录用户类型  proxy：0  shop：1
  		userId:uni.getStorageSync("userId") == ""? "": parseInt(uni.getStorageSync("userId")),
  	  };
  	  findUserMoney(params).then((res: any) => {
  	      if(res.data.code==200){
			  this.allYuMoney = res.data.data.usableBlance
  	      }else{
  	      
  	      }
  	  });
  }
  //余额付款
  saveOrderByBalance(postMoney:any,deliverType:any){ //postMoney邮费  deliverType取货方式
	  
	  uni.showLoading({
	  	title: '加载中'
	  });
	  let params = {
	    	goodsCartIds:JSON.stringify(this.carGoodsids),//
			addressId:this.addressDic.id,
			freight:postMoney,
			deliverType:parseInt(deliverType),
			orderNo:this.orderNum,
	    	userId:uni.getStorageSync("userId") == ""? "": parseInt(uni.getStorageSync("userId")),
	  };
	  console.log('++++++++++++++++++++订单参数2：' + JSON.stringify(params) )
	  saveOrderByBalance(params).then((res: any) => {
	    console.log('++++++++++++++++++++余额支付订单22：' + JSON.stringify(res.data) )
		uni.hideLoading();
		// debugger
	      if(res.data.code==200){  
			  this.paySuccess = {show:true,label:'完成'};
	      }else{
			  // this.paySuccess = {show:true,label:'返回'};
			  uni.showToast({
			      title: res.data.message,
				  icon:"none",
			      duration: 2000
			  });
	      }
	  });
  }
  //保存订单
  saveOrder(postMoney:any,deliverType:any){
	  
	  console.log('zhifubs支付')


    var phone = uni.getStorageSync("otherData").phone; //截取后4位
      var phoneS = phone.substring(phone.length - 4);
      console.log(phoneS, "phoneS");
      var timestamp = "O" + new Date().getTime() + phoneS.toString();

      uni.setStorage({
        key: "timestamp",
        data: timestamp,
        success: function () {
          setTimeout(() => {
            console.log(uni.getStorageSync("timestamp"), "99999998888888");
          }, 600);
        },
      });

	  let params = {
	    goodsCartIds:JSON.stringify(this.carGoodsids),//
	  	addressId:this.addressDic.id,
			freight:postMoney,
			deliverType:parseInt(deliverType),
			orderNo:timestamp,
	    userId:uni.getStorageSync("userId") == ""? "": parseInt(uni.getStorageSync("userId")),
	  };
	  console.log('++++++++++++++++++++1113：' + JSON.stringify(params) )

	  saveOrder(params).then((res: any) => {

	    console.log('++++++++++++++++++++saveOrder：' + JSON.stringify(res.data) )
	      if(res.data.code==200){

        console.log("进入");

          let data=`http://cdb.lianmengxiton.cn/app/posOrder/aliPay?userId=${uni.getStorageSync("userId")}&orderNo=${uni.getStorageSync("timestamp")}`
				
				console.log(data,'datadatadatadata') 

          // uni.redirectTo({
          //   url: `./link?data=${data}`,
          // });
		  
		    uni.redirectTo({
		              url: `../../pages/item/membershipUp/link?data=${data}`,
		            });

          AppModule.orderLinkAction(data)

	  			// this.aliPay()
	      }else{
			  console.log('9999')
				uni.showToast({
					title: '该订单已失效',
					icon:'none',
					duration: 2000
				});
				
	      }
	  });
  }
  //支付宝支付
  aliPay(){
	  let params = {
	  		orderNo:this.orderNum,
	    	userId:uni.getStorageSync("userId") == ""? "": parseInt(uni.getStorageSync("userId")),
	  };
	  console.log('++++++++++++++++++++订单参数1：' + JSON.stringify(params) )
	  aliPay(params).then((res: any) => {
	    console.log('++++++++++++++++++++余额支付订单11：' + JSON.stringify(res.data) )
	    if(res.data.code==200){
	  		this.paySuccess = {show:true,label:'完成'};
	    }else{
			this.paySuccess = {show:true,label:'返回'};
	    }
	  });
  }
  //确认支付
  addPay(){
	  if(this.payType == 'ye'){

		  if(this.fastMailName == '自提'){
			  this.saveOrderByBalance(0,0)
		  }else if(this.fastMailName == '普通快递'){
			  this.saveOrderByBalance(this.postMoney,1)
		  }
	  }else if(this.payType == 'zfb'){

		  if(this.fastMailName == '自提'){
		  		this.saveOrder(0,0)
		  }else if(this.fastMailName == '普通快递'){

		  		this.saveOrder(this.postMoney,1)

		  }

	  }else{
		  
	  }
	 // this.saveOrderByBalance()
  }
  //支付完成弹窗
  payClick(){
	  if(this.paySuccess.label == '完成'){
		  uni.navigateBack({
		    delta: 2,
		  });
		  this.paySuccess = {show:false,label:'完成'};
	  }else if(this.paySuccess.label == '返回'){
		  this.paySuccess = {show:false,label:'完成'};
	  }
  }
  //邮寄方式的按钮
  distrM() {
    this.sheetShow = true;
  }
  //邮寄方式 选中的按钮
  sheetClick(index:any){
	  this.fastMailName = this.sheetList[index].text;
	  if(this.fastMailName == '普通快递'){
		  this.allMoney = parseFloat(this.tipMoney) + parseFloat(this.postMoney)
	  }else if(this.fastMailName == '自提'){
		  this.allMoney = parseFloat(this.tipMoney)
	  }
  }
  //支付方式按钮
  payTypeClick(type:any){
	  this.payType = type;
  }

  BackM(){
	  uni.navigateBack({
	    delta: 1,
	  });
  }
  addressM(){
        uni.navigateTo({
      url: './address'
      });
  }
}
</script>

<style  lang="scss"  scoped>
.definite {
  font-family: PingFang SC;
  background: #f3f5f7;
  height: 100%;
}
uni-page-body {
  height: 100%;
}
.top-bar {
  height: 2.75rem;
  background: #02af74;
  box-shadow: 0rem 0rem 0rem 0rem rgba(204, 204, 204, 0.35);
}
.top-content {
  font-size: 0.7rem;
  font-family: PingFang SC;
  font-weight: 500;
  color: #ffffff;
  text-align: center;
  line-height: 2.75rem;
}
.top {
  position: relative;
  padding: 0.7rem 0.3rem;
  margin-bottom: 0.2rem;
  background: #ffffff;
}
.map {
  float: left;
  height: 3rem;
  width: 1.7rem;
}
.item {
  font-weight: 500;
  color: #666666;
  font-size: 0.7rem;
  font-family: PingFang SC;
  padding-bottom: 0.3rem;
}
.name {
  font-weight: 500;
}
.tele {
  float: right;
  padding-right: 3rem;
}
.address {
  width: 17rem;
  font-size: 0.7rem;
  font-family: PingFang SC;
  font-weight: 400;
  color: #666666;
  line-height: 0.81rem;
  font-weight: 500;
}
.item-content {
  padding: 0.4rem;
  height: 5.6rem;
  background: #f3f3f3;
  font-family: PingFang SC;
  margin-bottom: 0.03rem;
  border-bottom: 0.03rem #e5e5e5 solid;
}
.image {
  float: left;
}
.image image {
  width: 4.6rem;
  height: 4.6rem;
}
.description {
  float: left;
  font-size: 0.7rem;
  padding-left: 0.5rem;
  width: 13.63rem;
  height: 2rem;
  font-family: PingFang SC;
  font-weight: 500;
  color: #333333;
  line-height: 0.98rem;
}
.type {
  float: left;
  width: 14rem;
  line-height: 1.5rem;
  padding-left: 0.5rem;
  font-size: 0.6rem;
  font-family: PingFang SC;
  font-weight: 500;
  color: #999999;
}
.money {
  float: left;
  font-size: 0.75rem;
  padding-left: 0.5rem;
  font-family: PingFang SC;
  font-weight: 500;
  color: #ff0000;
}
.num {
  float: right;
  font-size: 0.7rem;
  font-family: PingFang SC;
  font-weight: 500;
  color: #000000;
}
.null {
  float: right;
  color: #999999;
  padding-right: 1rem;
}
.have {
  float: right;
  padding-right: 1rem;
}
.item-one {
  position: relative;
  padding: 0.7rem;
  font-size: 0.7rem;
  font-family: PingFang SC;
  font-weight: 500;
  color: #333333;
  background: #ffffff;
  margin-bottom: 0.1rem;
}
.top-image {
  position: absolute;
  top: 1.6rem;
  right: 0.5rem;
  width: 0.5rem;
  height: 0.85rem;
  color: #666666;
}
.image-one {
  position: absolute;
  top: 0.8rem;
  right: 0.5rem;
  width: 0.5rem;
  height: 0.85rem;
  color: #666666;
}
.button {
  float: right;
  width: 29%;
  font-size: 0.8rem;
  font-family: PingFang SC;
  font-weight: 500;
  color: #ffffff;
  line-height: 2.5rem;
  height: 2.5rem;
  background: #02af74;
  border-radius: 0;
  margin-left: 1rem;
}
.item-two {
  position: relative;
  height: 1rem;
  padding: 0.5rem;
  font-size: 0.7rem;
  font-family: PingFang SC;
  font-weight: 500;
  background: #ffffff;
  margin-bottom: 0.7rem;
}
.total {
  position: absolute;
  right: 0.6rem;
}
.one-image {
  position: absolute;
  top: 0.5rem;
  width: 1.5rem;
  height: 1.1rem;
}
.two-image {
  position: absolute;
  right: 0.5rem;
  bottom: 0.2rem;
 width: 1.2rem;
height: 1.2rem;
top: 0.6rem;

}
.three-image {
  position: absolute;
  top: 0.5rem;
  width: 1.1rem;
  height: 1.1rem;
}

.footP {
  position: fixed;
  bottom: 0;
  background-color: white;
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
.content-bottom {
  margin: 1rem;
}

.car-content {
  padding: 0rem 0.5rem 0.5rem 0.5rem;
}

.foot-right {
  display: flex;
}

.settle {
  background-color: #02af74;
  height: 100%;
  width: 5rem;
  text-align: center;
  font-size: 0.8rem;
  font-family: PingFang SC;
  font-weight: 400;
  color: white;
  margin-left: 1rem;
}
.shareModal {
  background: rgba(0, 0, 0, 0.2);
  height: 100vh;
  position: absolute;
  top: 0;
  width: 100%;
}
.modal-bottom-left {
  display: flex;
}
.modal-bottom {
  background-color: white;
  margin-top: -3px;
  padding: 0.3rem;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.imageP {
  background: rgba(0, 0, 0, 0.6);
  width: 100vw;
  text-align: center;
}

.threeQ {
  color: white;
  /* background-color: red; */
  background: rgba(0, 0, 0, 0.6);
  display: flex;
  justify-content: center;
}
.threeQ-image {
  width: 2.5rem;
}
</style>